package com.yasabu.wuvtdroid;

import java.io.IOException;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AsyncPlayer;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class WuvtStream extends Service {
	public static final String WUVT_HI = "http://engine.collegemedia.vt.edu:8000/wuvt.ogg";
	public static final String WUVT_ME = "http://engine.collegemedia.vt.edu:8000/wuvt-1b.ogg";
	public static final String WUVT_LO = "http://engine.collegemedia.vt.edu:8000/wuvt-du.ogg";
	public static final String DEBUG_STREAM_MP3 = "http://whrwfm.org:8080/lo";
	public static final String DEBUG_STREAM_OGG = "http://voxnoctem.de:9113/low.ogg";
	public static final String LATEST_TRACK_URL = "http://www.wuvt.vt.edu/playlists/latest_track_xml.php";
	List<String> wuvtInfo;
	MediaPlayer mp;
	AsyncPlayer ap;
	
    private NotificationManager mNM;

    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class LocalBinder extends Binder {
        WuvtStream getService() {
            return WuvtStream.this;
        }
    }

    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	ap = new AsyncPlayer("wuvt-stream");
    	// Display a notification about us starting.  We put an icon in the status bar.
        showNotification();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        try {
    		mp.setDataSource(getBaseContext(),Uri.parse(WUVT_HI));
    		mp.prepare();
    		mp.start();
    	}
    	catch (IOException e) {
    		mp.release();
    	}
    	/* Example Response: 
			<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
			<!-- Last-Modified: Sun, 14 Nov 2010 01:47:50 EST --><current_track> 
				<artist>Ecstatic Sunshine</artist> 
				<title>Herrons</title> 
				<album>Way</album> 
				<label>Cardboard</label> 
				<dj>AWESOME SHOW OF AWESOME</dj> 
				<time>1:47 AM</time> 
				<date>Nov 14, 2010</date> 
			</current_track>    	 
    	 */
    	HttpClient hc = new DefaultHttpClient();
    	try {
    		hc.execute((HttpUriRequest)Uri.parse(LATEST_TRACK_URL));
    	}
    	catch (ClientProtocolException e) {
    	}
    	catch (IOException e) {
    	}
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        // Cancel the persistent notification.
        mNM.cancel(R.string.wuvt_started);

        // Tell the user we stopped.
        Toast.makeText(this, R.string.wuvt_stopped, Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
    private final IBinder mBinder = new LocalBinder();

    /**
     * Show a notification while this service is running.
     */
    private void showNotification() {
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.wuvt_started);

        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.icon, text,
                System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, WuvtRadio.class), 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, "WUVT", text, contentIntent);

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        mNM.notify(R.string.wuvt_started, notification);
    }
    
    private void lastfmScrobble() {
    	Boolean hasPlayed = true;
    	if (hasPlayed)
    	{
	    	Intent i = new Intent("fm.last.android.playbackcomplete");
	    	sendBroadcast(i);
    	}
    	
    	String librefmUrl = "turtle.libre.fm";
    	Intent i = new Intent("fm.last.android.metachanged");
    	i.putExtra("artist", wuvtInfo.get(0));
    	i.putExtra("album", wuvtInfo.get(1));
    	i.putExtra("track", wuvtInfo.get(2));
    	i.putExtra("duration", 3*1000);
    	sendBroadcast(i);
    }
}

